package br.com.ambgis.sicap;

import static br.com.ambgis.sicap.Constants.DEBUG;
import static br.com.ambgis.sicap.Constants.TAG;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import au.com.bytecode.opencsv.CSVWriter;

public class MainActivity extends Activity implements OnClickListener {

	private File dataDir;

	private ImageView addSignImage;
	private ImageView manageSignImage;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		dataDir = getExternalFilesDir(null);
		Log.d(TAG, "Sicap data directory: " + dataDir);
		dataDir.mkdirs();
		if (!dataDir.exists()) {
			final String message = "Can't create directory " + dataDir;
			Log.e(TAG, message);
		}

		addSignImage = (ImageView) findViewById(R.id.actionadd);
	    addSignImage.setOnClickListener(this);
	    manageSignImage = (ImageView) findViewById(R.id.actionmanage);
	    manageSignImage.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.actionadd:
			new AlertDialog.Builder(MainActivity.this)
					.setTitle(R.string.capture)
					.setItems(R.array.menu_add_sign_entries, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								switch (id) {
								case 0:
									Intent placaRuaIntent = new Intent(MainActivity.this, CapturaPlacaRuaActivity.class);
									startActivity(placaRuaIntent);
									break;
								case 1:
									Intent placaCasaintent = new Intent(MainActivity.this, CapturaPlacaCasaActivity.class);
									startActivity(placaCasaintent);
									break;
								default:
									Log.w(TAG, "Unexpected click from " + id);
								}
							}
					}).create().show();
			break;
		case R.id.actionmanage:
			new AlertDialog.Builder(MainActivity.this)
			.setTitle(R.string.manage)
			.setItems(R.array.menu_manage_entries, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,	int id) {
						switch (id) {
						case 0:
							Intent gerenciadorIntent = new Intent(MainActivity.this, GerenciadorPlacaActivity.class);
							startActivity(gerenciadorIntent);
							break;
						case 1:
							new FileExportTask().execute((Object[]) null);
							break;
						default:
							Log.w(TAG, "Unexpected click from " + id);
						}
					}
			}).create().show();
			break;
		default:
			Log.w(TAG, "Unexpected click from " + v.getId());
			break;
		}
	}

	class FileExportTask extends AsyncTask<Object, Object, File>  {

		@Override
		protected File doInBackground(Object... params) {
			DbHelper helper = new DbHelper(MainActivity.this);
			PlacaDao dao = new PlacaDao(helper.getWritableDatabase());
			File f = new File(dataDir, FileNameUtils.getNextFilename("csv"));
			CSVWriter writer = null;
			try {
				writer = new CSVWriter(new PrintWriter(f), ';');

				Cursor cursor = dao.getAllAsCursor();
				writer.writeAll(cursor, /* includeColumnNames */ true);
				cursor.close();

				//Exclusao logica de todas as placas que foram exportadas
				dao.deleteAll();

				return f;
			} catch (FileNotFoundException e) {
				throw new RuntimeException("Can't create file " + f, e);
			} finally {
				dao.close();
				try {
					if (writer != null) writer.close();
				} catch (IOException e) {
					if (DEBUG) Log.d(TAG, "fail to close writer, ignore", e);
				}
			}
		}

		@Override
		protected void onPostExecute(File result) {
			//TODO externalizar mensagem abaixo
			if (result != null && result.exists()) {
				Toast.makeText(MainActivity.this, "Arquivo gerado com sucesso", Toast.LENGTH_SHORT).show();
			}
		}
	}

}
